import React from 'react';
import PropTypes from 'prop-types';
import { Form, Col, Select } from 'antd';
import { validEmoji, mapTypeToComponent } from './utils/util';
import DynamicFieldSet from './DynamicFieldSet';

const FormItem = Form.Item;
const { OptGroup } = Select;

function GlobalFormItem({ itemSet, column, labelBasicSpan, totalSpan }) {
  const {
    type = 'input', // 类型
    title, // 标签
    dataIndex, // 入参名
    invalid = false, // 是否失效隐藏
    layoutProps = {}, // 布局相关
    validOptions = {}, // 校验相关
    optionsData = [], // 下拉框数据
    models = [], // 下拉框数据对应的字段名['label','value']
    props = {}, // 组件原生的属性
    listFormSet = [], // 动态列表的配置
    render = '',
    ...restItemProps
  } = itemSet;
  console.log("restItemProps", restItemProps)
  const name = dataIndex;
  const label = title;
  if (invalid) {
    return null;
  }
  const componentType = type.toLowerCase();
  // 组件类型
  const {
    WrappedComponent,
    defaultProps = {},
    childStyle,
    SubComponent,
    normalize,
  } = mapTypeToComponent[componentType];


  // 是否有子组件
  const isOptionFields = [
    'select',
    'selectgroup',
    'radiogroup',
    'radiogroupbutton',
    'checkboxgroup',
  ].includes(componentType);
  const [vauleKey = 'value', labelKey = 'label'] = models;

  // 布局相关
  const span = layoutProps.span === undefined ? 1 : Math.min(layoutProps.span, column); // 列占比数
  const colSpan = Math.ceil(24 / column) * span;
  const labelSpan = label ? Math.ceil(labelBasicSpan / (layoutProps.span || 1)) : 0;
  const newLayOutProps = {
    labelCol: { span: labelSpan },
    wrapperCol: { span: totalSpan - labelSpan },
    label,
    ...layoutProps,
  };

  // 校验配置，全局控制输入不能有emoji,除查询表单
  if (['input', 'password', 'textarea'].includes(componentType)) {
    validOptions.rules = validOptions.rules || [];
    const commonRules = [
      {
        validator: validEmoji,
      },
    ];
    // 判断是否已经加入
    const hasCommon = validOptions.rules.some((element) => element.validator === validEmoji);
    const hasEmptyRule = validOptions.rules.some((element) => element.required);
    if (!hasCommon) {
      if (hasEmptyRule) {
        validOptions.rules.push({
          whitespace: true,
          message: '不能全为空格',
        });
      }
      validOptions.rules = [].concat(commonRules, validOptions.rules);
    }
  }

  const newValidOptions = {
    validateFirst: true, // validateFirst：当某一规则校验不通过时，是否停止剩下的规则的校验
    normalize,
    ...validOptions,
  };

  let children = null;

  if (componentType === 'text') {
    children = layoutProps.children || <div></div>;
  }

  if (componentType === 'list') {
    children = <DynamicFieldSet name={name} listFormSet={listFormSet} {...props} />;
  }

  if (componentType === 'custom') {
    children = render
  }

  console.log("name", name)
  return (
    <Col span={colSpan}>
      {
        <FormItem
          labelCol={{ span: colSpan }}
          name={name}
          {...restItemProps}
          {...newLayOutProps}
          {...newValidOptions}
        >
          {children ? (
            children
          ) : (
              <WrappedComponent {...defaultProps} {...props}>
                {isOptionFields
                  ? optionsData.map((v) => {
                    if (componentType == 'select') console.log("v", v, vauleKey)
                    if (componentType === 'selectgroup') {
                      return (
                        <OptGroup label={v[labelKey]} key={v[labelKey]}>
                          {v.children &&
                            v.children.map((child) => (
                              <SubComponent
                                key={String(child[vauleKey])}
                                value={child[vauleKey]}
                                style={childStyle}
                                disabled={child.disabled}
                              >
                                {child[labelKey]}
                              </SubComponent>
                            ))}
                        </OptGroup>
                      );
                    }
                    return (
                      <SubComponent
                        key={String(v[vauleKey])}
                        value={v[vauleKey]}
                        style={childStyle}
                        disabled={v.disabled}
                      >
                        {v[labelKey]}
                      </SubComponent>
                    );
                  })
                  : null}
              </WrappedComponent>
            )}
        </FormItem>
      }
    </Col>
  );
}
GlobalFormItem.propTypes = {
  itemSet: PropTypes.object, // 表单字段配置项
  gutter: PropTypes.number, // 输入项之间的间隔
  column: PropTypes.number, // 一行几列
  labelBasicSpan: PropTypes.number, //
};

GlobalFormItem.defaultProps = {
  itemSet: {},
  gutter: 0,
  column: 3,
  labelBasicSpan: 8,
  totalSpan: 22,
};

export default GlobalFormItem;
